#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
#include <qlogging.h>
#include <qobject.h>
#include <qtypes.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow) {
  ui->setupUi(this);

  topic_1 = "client_1";
  topic_2 = "client_2";

  ui->pbtn_connect_1->setText("连接云服务器");

  setLedColor(ui->lamp_1, "ff0000", 30);

  ui->txt_host->setText("8.152.213.152");
  ui->spinBox_port->setValue(1883);

  client_1 = new QMqttClient(this);

  // 云服务器已连接
  connect(client_1, &QMqttClient::connected, this, [=]() {
    QString strTime =
        QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz: ");
    ui->txt_msg_1->appendPlainText(strTime);
    ui->txt_msg_1->appendPlainText("云服务器已连接");
    setLedColor(ui->lamp_1, "00ff00", 30);

    // 订阅1
    auto subscription = client_1->subscribe(topic_1);
    if (!subscription) {
      QMessageBox::critical(
          this, "Error", "Could not subscribe. Is there a valid connection?");
      return;
    }
  });

  // 云服务器已断开
  connect(client_1, &QMqttClient::disconnected, this, [=]() {
    QString strTime =
        QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz: ");
    ui->txt_msg_1->appendPlainText(strTime);
    ui->txt_msg_1->appendPlainText("云服务器已断开");
    setLedColor(ui->lamp_1, "ff0000", 30);
    client_1->unsubscribe(topic_1);
  });

  // 收到消息
  connect(client_1, &QMqttClient::messageReceived, this,
          [this](const QByteArray &message, const QMqttTopicName &topic) {
            QString strTime = QDateTime::currentDateTime().toString(
                "yyyy-MM-dd hh:mm:ss.zzz: ");
            const QString content = " Received Topic: " + topic.name() +
                                    "\n"
                                    " Message: " +
                                    message + u'\n';
            ui->txt_rec_1->appendPlainText(strTime);
            ui->txt_rec_1->appendPlainText(content);
          });
}

MainWindow::~MainWindow() { delete ui; }

void MainWindow::on_pbtn_clear_1_clicked() {}

void MainWindow::on_pbtn_save_1_clicked() {}

void MainWindow::on_pbtn_publish_1_clicked() {
  // if(client_1->publish("Client_1",ui->txt_publish_1->text().toUtf8())==-1)

  if (client_1->publish(QString(topic_1), ui->txt_publish_1->text().toUtf8()) ==
      -1)
    QMessageBox::critical(this, "Error", "Could not publish message");
}

void MainWindow::on_txt_clear_msg_1_clicked() {}

void MainWindow::on_pbtn_connect_1_clicked() {

  // 设置地址
  client_1->setHostname(ui->txt_host->text());
  // 设置端口号
  client_1->setPort(static_cast<quint16>(ui->spinBox_port->value()));

  if (ui->pbtn_connect_1->text() == "连接云服务器") {
    client_1->connectToHost();
    ui->pbtn_connect_1->setText("断开云服务器");
  } else {
    client_1->disconnectFromHost();
    ui->pbtn_connect_1->setText("连接云服务器");
  }
}

/****************************以下为工具包******************************/

void MainWindow::saveFile() {
  QString fileName = QFileDialog::getSaveFileName(
      this, "保存文件", "", "Text (*.txt);;Excel (*.xlsx);;Dat (*.dat)");

  if (!fileName.isEmpty()) {
    // 如果用户选择了文件路径，则保存数据到文件
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly)) {
      QMessageBox::warning(nullptr, "错误", "无法打开文件!");
      return;
    }
    QTextStream out(&file);
    out << ui->txt_rec_1->toPlainText();
    file.close();
  }
}

void MainWindow::setLedColor(QLabel *label, QString str, int size) {

  label->setText("");
  QString min_width = QString("min-width: %1px;").arg(size);
  QString min_height = QString("min-height: %1px;").arg(size);
  QString max_width = QString("max-width: %1px;").arg(size);
  QString max_height = QString("max-height: %1px;").arg(size);

  QString border_radius = QString("border-radius: %1px;").arg(size / 2);
  QString border = QString("border:0px solid black;");

  QString background = "background-color:#" + str;

  const QString Sheetstyle1 = min_width + min_height + max_width + max_height +
                              border_radius + border + background;
  label->setStyleSheet(Sheetstyle1);
}